﻿using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Enterprise
{
    /// <summary>
    /// 获取企业
    /// </summary>
    public class SearchEnterpriseHandler : IRequestHandler<SearchEnterpriseCommand, Result>
    {
        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepository<Enterprises> _enterpriseRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchEnterpriseHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="enterpriseRepository"></param>
        /// <param name="logger"></param>
        public SearchEnterpriseHandler(IBaseRepository<Enterprises> enterpriseRepository,
                                       ILogger<SearchEnterpriseHandler> logger)
        {
            _enterpriseRepository = enterpriseRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchEnterpriseCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //获取企业信息
                var query = await (await _enterpriseRepository.GetAll()).ToListAsync();
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取企业信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取企业信息异常" + ex.Message;
                _logger.LogError("获取企业信息异常" + ex.Message);
            }
            return result;
        }
    }
}
